package com.yuan.blog.core.utils;



import com.sun.mail.util.MailSSLSocketFactory;
import com.yuan.blog.dto.EmailDto;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.security.GeneralSecurityException;
import java.util.Properties;

/**
 * @program: Mail
 * @description: 发送邮件
 * @author: yuan_boss
 * @create: 2022-12-02 12:05
 **/
public class MailUtil {
    public static void main(String[] args) throws Exception {

        EmailDto emailDto = new EmailDto("1928627476@qq.com", "测试发送QQ邮件", "QQ邮件内容");
        sendSimpleMail(emailDto);
        sendPicMail("1928627476@qq.com","测试图片发送","F:\\桌面\\yuanboss\\yuan.jpeg","yuanboss.jpeg","图片邮件内容");
        sendFileMail("1928627476@qq.com","测试文件发送标题","测试文件内容","F:\\桌面\\yuanboss\\yuan.jpeg","yuanboss.jpeg","F:\\桌面\\yuanboss\\yuan.txt","yuan.txt");
    }


    //发送简单邮件
    public static void sendSimpleMail(EmailDto emailDto) throws GeneralSecurityException, MessagingException {
        //获取户端与邮箱服务器的Session对象
        Session session = getSession();
        //通过session得到建立连接的transport对象
        Transport ts = getTransport(session);
        //创建邮件
        Message message = createSimpleMail(session, emailDto.getReceive(), emailDto.getTitle(), emailDto.getContent());
        //发送邮件
        ts.sendMessage(message,message.getAllRecipients());
        //关闭连接
        ts.close();
    }
    //发送图片邮件
    public static void sendPicMail(String receive,String title,String path,String picName,String content) throws GeneralSecurityException,MessagingException {
        //1.获取户端与邮箱服务器的Session对象
        Session session = getSession();
        //2.通过session得到建立连接的transport对象
        Transport ts = getTransport(session);
        //3.创建邮件
        Message message = createPicMail(session, receive, title, path, picName, content);
        //5.发送邮件
        ts.sendMessage(message,message.getAllRecipients());
        //6.关闭连接
        ts.close();
    }

    //发送文件邮件
    public static void sendFileMail(String receive,
                                    String title, String content,String picPath,String PicName,
                                    String filePath,String fileName) throws GeneralSecurityException, MessagingException, MessagingException {
        //1.获取户端与邮箱服务器的Session对象
        Session session = getSession();
        //2.通过session得到建立连接的transport对象
        Transport ts = getTransport(session);
        //3.创建邮件
        MimeMessage message = createFileMail(session, receive, title, content, picPath, PicName, filePath, fileName);
        //5.发送邮件
        ts.sendMessage(message,message.getAllRecipients());
        //6.关闭连接
        ts.close();

    }
    //创建简单邮件
    public static Message createSimpleMail(Session session,String receive,String title,String content) throws MessagingException {
        //创建邮件：写文件
        //注意需要传递session
        MimeMessage message=new MimeMessage(session);
        //指明邮件的发件人
        message.setFrom(new InternetAddress("1928627476@qq.com"));
        //指明邮件的收件人
        message.setRecipient(Message.RecipientType.TO,new InternetAddress(receive));
        //邮件标题
        message.setSubject(title);
        //邮件的文本内容
        message.setContent(content,"text/html;charset=UTF-8");
        //设置抄送人
        message.setRecipients(Message.RecipientType.CC,InternetAddress.parse("1928627476@qq.com"));
        return message;

    }
    //创建图片邮件
    public static MimeMessage createPicMail(Session session,String receive,
                                            String title,String path,
                                            String picName,String content) throws MessagingException {
        //创建邮件：写文件
        //注意需要传递session
        MimeMessage message=new MimeMessage(session);
        //指明邮件的发件人
        message.setFrom(new InternetAddress("1928627476@qq.com"));
        //指明邮件的收件人
        message.setRecipient(Message.RecipientType.TO,new InternetAddress(receive));
        //邮件标题
        message.setSubject(title);
        //设置抄送人
        message.setRecipients(Message.RecipientType.CC,InternetAddress.parse("1928627476@qq.com"));

        //邮件的文本内容
        //=================================准备图片数据=======================================
        MimeBodyPart image=new MimeBodyPart();
        //图片需要经过数据化的处理,path为图片路径
        DataHandler dh=new DataHandler(new FileDataSource(path));
        //在part中放入这个处理过图片的数据
        image.setDataHandler(dh);
        //给这个part设置一个ID名字(图片名字)
        image.setContentID(picName);

        //准备正文的数据
        MimeBodyPart text=new MimeBodyPart();
        text.setContent(content,"text/html;charset=UTF-8");

        //描述数据关系
        MimeMultipart mm=new MimeMultipart();
        mm.addBodyPart(text);
        mm.addBodyPart(image);
        mm.setSubType("related");

        //设置到消息中，保存修改
        message.setContent(mm);
        message.saveChanges();
        return message;
    }

    //创建文件邮件
    public static MimeMessage createFileMail(Session session,String receive,
                                             String title, String content,String picPath,String PicName,
                                             String filePath,String fileName) throws MessagingException {
        //创建邮件：写文件
        //注意需要传递session
        MimeMessage message=new MimeMessage(session);
        //指明邮件的发件人
        message.setFrom(new InternetAddress("1928627476@qq.com"));
        //指明邮件的收件人
        message.setRecipient(Message.RecipientType.TO,new InternetAddress(receive));
        //设置抄送人
        message.setRecipients(Message.RecipientType.CC,InternetAddress.parse("1928627476@qq.com"));
        //邮件标题
        message.setSubject(title);
        //邮件的文本内容
        //=================================准备正文数据
        MimeBodyPart text=new MimeBodyPart();
        text.setContent(content,"text/html;charset=UTF-8");
        //=================================准备图片数据
        MimeBodyPart image=new MimeBodyPart();
        //图片需要经过数据化的处理
        DataHandler dh=new DataHandler(new FileDataSource(picPath));
        //在part中放入这个处理过图片的数据
        image.setDataHandler(dh);
        //给这个part设置一个ID名字
        image.setContentID(PicName);

        //=================================准备附件数据
        MimeBodyPart body1= new MimeBodyPart();
        body1.setDataHandler(new DataHandler(new FileDataSource(filePath)));
        body1.setFileName(fileName);

        //描述数据关系
        MimeMultipart mm=new MimeMultipart();
        mm.addBodyPart(body1);
        mm.addBodyPart(text);
        mm.addBodyPart(image);
        mm.setSubType("mixed");

        //设置到消息中，保存修改
        message.setContent(mm);
        message.saveChanges();
        return message;
    }
    //获取户端与邮箱服务器的Session对象
    public static Session getSession() throws GeneralSecurityException {
        Properties prop = new Properties();
        prop.setProperty("mail.host", "smtp.qq.com");///设置QQ邮件服务器
        prop.setProperty("mail.transport.protocol", "smtp");///邮件发送协议
        prop.setProperty("mail.smtp.auth", "true");//需要验证用户密码

        //QQ邮箱需要设置SSL加密，其他邮箱不需要
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        prop.put("mail.smtp.ssl.enable", "true");
        prop.put("mail.smtp.ssl.socketFactory", sf);

        //使用javaMail发送邮件的5个步骤
        //1.创建定义整个应用程序所需要的环境信息的session对象

        //QQ才有！其他邮箱就不用,创建客户端与邮箱服务器的Session对象
        Session session = Session.getDefaultInstance(prop, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                //发件人邮件用户名、授权码
                return new PasswordAuthentication("1928627476@qq.com", "drlndxznqvmbchhi");
            }
        });

        //开启session的debug模式，这样可以查看到程序发送Email的运行状态
        session.setDebug(true);
        return session;
    }
    //通过session得到建立连接的transport对象并且建立客户端与邮箱服务器的连接
    public static Transport getTransport(Session session) throws MessagingException {
        //2.通过session得到transport对象
        Transport ts = session.getTransport();

        //3.使用邮箱的用户名和授权码连上邮件服务器
        ts.connect("smtp.qq.com", "1928627476@qq.com", "drlndxznqvmbchhi");
        return ts;
    }
}
